import Toast from '@vant/weapp/toast/toast'
import { authorization } from '../../../../utils/location'
const app = getApp()
Page({
    data: {
        customerTagOptions: [
            { text: '新客户', value: 'new' },
            { text: '老客户', value: 'old' },
            { text: '潜在客户', value: 'potential' }
        ],
        customer: ['重点客户', 'VIP客户', '一般客户', '无价值客户', '沉默客户'],
        orderPlatformOptions: [
            { label: '淘宝', value: 'taobao', checked: false },
            { label: '京东', value: 'jd', checked: false },
            { label: '拼多多', value: 'pdd', checked: false }
        ],
        showPicker: false,
        popupFlag: false,
        customer_mobile: '',
        customer_type: '',
        result: [],
        otherInputValue: '',
        showOtherInput: false,
        selectedDate: '',
        showDatePicker: false,
        customer_shop: '',
        tempFilePaths: [],
        longitude: '',
        latitude: '',
        customer_name: '',
        customer_mobile: '',
        customer_remarks: '',
        customer_type: '',
        access_token: '',
        wechatFilePaths: [],

    },
    onLoad(options) {
        let access_token = app.session.access_token || wx.getStorageSync('access_token')
        console.log(access_token)
        this.setData({
            access_token,
        })
    },
    // 显示日期选择器弹窗
    showPickerPopup() {
        this.setData({
            showPicker: true
        });
    },
    // 关闭日期选择器弹窗
    onDatePickerClose() {
        this.setData({
            showDatePicker: false
        });
    },
    // 处理 picker 选择变化

    onpickeCancel() {
        this.setData({
            showDatePicker: false
        });

    },
    onpickerConfirm(event) {
        const { picker, value, index } = event.detail;
        console.log(value)
        this.setData({
            showPicker: false,
            customer_type: value
        });
    },
    // 复选框选择变化事件处理函数
    ontypeChange(e) {
        const value = e.detail;
        this.setData({
            result: value,
            // 若选择结果包含“其他”，显示输入框
            showOtherInput: value.includes('其他')
        });
    },
    // 其他输入框输入事件处理函数
    onOtherInputChange(e) {
        this.setData({
            otherInputValue: e.detail
        });
    },

    onDateConfirm(event) {
        console.log(event);
        const value = event.detail;
        // 格式化日期的函数
        const formatDate = (date) => {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}/${month}/${day}`;
        };
        // 对获取到的日期进行格式化
        const formattedDate = formatDate(new Date(value));
        console.log(formattedDate);
        this.setData({
            showDatePicker: false,
            selectedDate: formattedDate
        });
    },
    showDatePickerPopup() {
        this.setData({
            showDatePicker: true
        });
    },
    onDateClose() {
        console.log("关闭")
        this.setData({
            showDatePicker: false
        });
    },
    onPlatChange(e) {
        const platform_difference = e.detail;
        // 清除之前的定时器
        this.setData({
            platform_difference
        });
    },

    async get_current_location() {
        let res = await authorization()
        console.log("authorization res", res);
        this.setData({
            longitude: res.longitude,
            latitude: res.latitude
        })
    },
    // 统一处理图片上传
    async handleAfterRead(e) {
        const { type } = e.currentTarget.dataset;
        const { file } = e.detail;
        let uploadFile = file;

        if (type === 'shopPhoto') {
            try {
                const currentTime = this.formatTime(new Date());
                const address = await this.getAddress();
                const watermarkedFilePath = await this.addWatermark(file, currentTime, address);
                uploadFile = { url: watermarkedFilePath };
            } catch (err) {
                console.error('添加水印失败:', err);
                wx.showToast({ title: '生成带水印图片失败~', icon: 'none' });
            }
        }

        await this.uploadFile(uploadFile, type);
    },
    // 添加水印
    async addWatermark(file, currentTime, address) {
        return new Promise((resolve, reject) => {
            const ctx = wx.createCanvasContext('watermarkCanvas');
            wx.getImageInfo({
                src: file.url,
                success: (res) => {
                    console.log("图片信息:", res);
                    console.log("图片宽度:", res.width);
                    console.log("图片高度:", res.height);
                    const imgWidth = res.width;
                    const imgHeight = res.height;
                    const canvasWidth = 300; // 画布宽度
                    const canvasHeight = 300; // 画布高度
                    let drawWidth, drawHeight, drawX, drawY;

                    // 计算图片按比例缩放后的宽高
                    if (imgWidth / imgHeight > canvasWidth / canvasHeight) {
                        drawWidth = canvasWidth;
                        drawHeight = (imgHeight * canvasWidth) / imgWidth;
                        drawX = 0;
                        drawY = (canvasHeight - drawHeight) / 2;
                    } else {
                        drawHeight = canvasHeight;
                        drawWidth = (imgWidth * canvasHeight) / imgHeight;
                        drawX = (canvasWidth - drawWidth) / 2;
                        drawY = 0;
                    }

                    // 设置画布尺寸
                    ctx.canvasWidth = canvasWidth;
                    ctx.canvasHeight = canvasHeight;

                    // 绘制图片
                    ctx.drawImage(file.url, drawX, drawY, drawWidth, drawHeight);

                    ctx.setFontSize(12);
                    ctx.setFillStyle('rgba(255, 255, 255, 0.8)');
                    if (address) {
                        ctx.fillText(`地址: ${address}`, 10, canvasHeight - 40);
                    }
                    ctx.fillText(`时间: ${currentTime}`, 10, canvasHeight - 10);
                    ctx.draw(false, () => {
                        wx.canvasToTempFilePath({
                            canvasId: 'watermarkCanvas',
                            success: (res) => resolve(res.tempFilePath),
                            fail: (err) => reject(err)
                        });
                    });
                },
                fail: (err) => reject(err)
            });
        });
    },
    // 获取地址
    async getAddress() {
        await this.get_current_location();
        const { longitude, latitude } = this.data;
        if (!longitude || !latitude) return '';

        return new Promise((resolve, reject) => {
            wx.request({
                url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=ANNBZ-KHK35-WPKIX-I2FVZ-PLPI2-RYB6J`,
                success: (res) => {
                    console.log("逆地理编码结果:", res.data);
                    if (res.data.status === 0) {
                        resolve(res.data.result.address);
                    } else {
                        reject(new Error('逆地理编码失败'));
                    }
                },
                fail: (err) => reject(err)
            });
        });
    },
    // 获取当前位置
    get_current_location() {
        return new Promise((resolve, reject) => {
            wx.getLocation({
                type: 'wgs84',
                success: (res) => {
                    this.setData({
                        longitude: res.longitude,
                        latitude: res.latitude
                    });
                    resolve();
                },
                fail: (err) => reject(err)
            });
        });
    },
    // 格式化时间
    formatTime(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 上传文件
    async uploadFile(file, type) {
        return new Promise((resolve, reject) => {
            wx.uploadFile({
                url: 'https://helper.fuduoduoshop.com/api/v1/file/images',
                filePath: file.url,
                header: {
                    'Content-Type': 'application/json',
                    'x-api-key': this.data.access_token
                },
                name: 'file',
                formData: {
                    drive: 'qiniu',
                    thumb: JSON.stringify([{ width: 100, height: 100 }])
                },
                success: (res) => {
                    console.log("上传成功", res)
                    try {
                        const response = JSON.parse(res.data);
                        if (response.code === 200) {
                            const updatedFile = { ...file, url: response.data.url };
                            if (type === 'shopPhoto') {
                                this.setData({
                                    tempFilePaths: [...this.data.tempFilePaths, updatedFile]
                                });
                            } else if (type === 'wechatScreenshot') {
                                this.setData({
                                    wechatFilePaths: [...this.data.wechatFilePaths, updatedFile]
                                });
                            }
                            resolve();
                        } else {
                            reject(new Error('文件上传失败'));
                        }
                    } catch (parseErr) {
                        reject(parseErr);
                    }
                },
                fail: (err) => reject(err)
            });
        });
    },

    imgDelete(event) {
        console.log("删除图片")
        let that = this
        let urlPath = event.detail.file.url
        wx.request({
            url: app.globalData.API + '/delivery/index/delete-qiniu-image',
            header: {
                'Content-Type': 'application/json',
                'x-api-key': that.data.access_token
            },
            data: {
                path: urlPath
            },
            method: 'POST',
            success: res => {
                if (res.data.code == 200) {
                    console.log(res)
                    const success = res.data.data
                    console.log(success)
                    if (success) {
                        let tempFilePaths = that.data.tempFilePaths
                        tempFilePaths = tempFilePaths.filter(item => item.url !== urlPath)
                        that.setData({
                            tempFilePaths
                        })
                    }
                }
            }
        })
    },

    async handleImageDelete(event, fileListKey) {
        const urlPath = event.detail.file.url;
        try {
            const res = await new Promise((resolve, reject) => {
                wx.request({
                    url: app.globalData.API + '/delivery/index/delete-qiniu-image',
                    header: {
                        'Content-Type': 'application/json',
                        'x-api-key': this.data.access_token
                    },
                    data: {
                        path: urlPath
                    },
                    method: 'POST',
                    success: resolve,
                    fail: reject
                });
            });

            if (res.data.code === 200 && res.data.data) {
                const fileList = this.data[fileListKey].filter(item => item.url !== urlPath);
                this.setData({
                    [fileListKey]: fileList
                });
            }
        } catch (err) {
            console.error('删除图片失败:', err);
        }
    },
    // 删除水印照片
    imgDeleteWithWatermark(event) {
        this.handleImageDelete(event, 'tempFilePaths');
    },

    // 删除无水印照片
    imgDeleteWithoutWatermark(event) {
        this.handleImageDelete(event, 'wechatFilePaths');
    },
    formSubmit(e) {
        const {
            search_mobile,
            customer_name,
            customer_mobile,
            customer_remarks,
            customer_type,
            result,
            otherInputValue,
            selectedDate,
            customer_shop,
            tempFilePaths,
            wechatFilePaths,
        } = this.data;
        // 收集表单数据
        const formData = {
            search_mobile,
            customer_name,
            customer_mobile,
            customer_remarks,
            customer_type,
            result,
            otherInputValue,
            selectedDate,
            customer_shop,
            // 提取图片 URL 数组
            tempFilePaths: tempFilePaths.map(file => file.url),
            wechatFilePaths: wechatFilePaths.map(file => file.url)

        };
        // 发送请求到后台
        wx.request({
            url: 'https://your-api-url.com/submit-order', // 替换为实际的后台接口地址
            method: 'POST',
            header: {
                'Content-Type': 'application/json',
                'x-api-key': this.data.access_token // 确保 access_token 存在于 data 中
            },
            data: formData,
            success: (res) => {
                if (res.data.code === 200) {
                    wx.showToast({
                        title: '提交成功',
                        icon: 'success'
                    });
                    // 可添加提交成功后的其他操作，如跳转页面
                } else {
                    wx.showToast({
                        title: '提交失败',
                        icon: 'none'
                    });
                }
            },
            fail: (err) => {
                console.error('请求失败:', err);
                wx.showToast({
                    title: '网络请求失败',
                    icon: 'none'
                });
            }
        });
    }
});